<?php 
namespace Home\Controller;

use Think\Controller;
class UserController extends Controller {
	//用户注册页面
	public function Reg(){
		if(IS_POST){
			//创建UsersModel的实例
			$user = D('Users');
			if(!$user->create()){//自动验证
				$return = ['success'=>false,'msg'=>$user->getError()];//自动验证不通过返回结果
			}else{
				//密码加盐+盐保存
				$salt = $this->creatSalt();//生成随机盐
				$user->password = md5($user->password.$salt);//密码加盐更安全
				$user->salt = $salt; //保存随机盐
				$user->acctype = $_POST['type'];//保存注册者的身份
				$user->add();
				$return = ['success'=>true,'msg'=>$salt]; //注册成功返回结果给前台
			}  

			echo json_encode($return);//给前台返回json格式的结果
			exit;
		}else{
			$this->display('register');//没POST就显示模板
		}
	}

	//用户登陆页面
	public function login(){
		if(IS_POST){
			$user = D('Users');
			$email = I('post.email');
			$users = $user->where(['email'=>$email])->find();
			if(!$users){
				$return = ['success'=>false,'msg'=>'邮箱没有找到,请确定是否注册!'];
			}else{
				$password = md5(I('post.password').$users['salt']);
				if($users['password'] == $password){
					//cookie加盐确保安全还有安全KEY加密顺序
					$key = md5($users['password'].$users['id'].C('C_SALT'));
					cookie('uid',$users['password']);
					cookie('sn',$users['uid']);
					cookie('key',$key);
					$return = ['success'=>true];
				}
			}
			echo json_encode($return);
			exit;
		}else{	
			$this->display('login');
		}
	}

	//退出登陆待做
	public function logout(){
		var_dump(cookie('tttt').'111');
	}

	//生成随机密码盐
	public function creatSalt(){
		$str = substr(str_shuffle('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'),0,8);
		return $str;
	}
	/**
	*
	*/
}
